package com.gotop.auth.granter;

import com.gotop.auth.service.IUserService;
import com.gotop.common.enums.EnumTokenGranter;
import com.gotop.common.utils.auth.SecureUtil;
import com.gotop.common.utils.auth.TokenConstant;
import com.gotop.common.utils.auth.TokenParameter;
import com.gotop.info.UserInfo;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @program: cem
 * @description:
 * @author: superfish
 * @create: 2020-12-17 16:05
 **/
@Component
@AllArgsConstructor
public class RefreshTokenGranter implements ITokenGranter {

    public static final String GRANT_TYPE = EnumTokenGranter.REFRESH_TOKEN_GRANTER.getMsg();

    private IUserService userService;

    @Override
    public UserInfo grant(TokenParameter tokenParameter) {
        String grantType = tokenParameter.getArgs().getStr("grantType");
        String refreshToken = tokenParameter.getArgs().getStr("refreshToken");
        UserInfo userInfo = null;
        if (StringUtils.isNoneBlank(grantType, refreshToken) && grantType.equals(TokenConstant.REFRESH_TOKEN)) {
            Claims claims = SecureUtil.parseJWT(refreshToken);
            String tokenType = String.valueOf(Objects.requireNonNull(claims).get(TokenConstant.TOKEN_TYPE));
            if (tokenType.equals(TokenConstant.REFRESH_TOKEN)) {
                userInfo= userService.userInfo(Long.parseLong(String.valueOf(claims.get(TokenConstant.USER_ID))));
            }
        }
        return userInfo;
    }
}
